package com.sg.file.receive.provider.util.filereceive;

import com.sg.file.common.conf.FileSizeTypeConf;
import com.sg.file.receive.api.dto.ByteFileReceiveRequest;
import com.sg.file.receive.api.dto.FileCreateDTO;
import com.sg.file.receive.provider.util.creator.FileInfoCreator;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.*;

/**
 * 字节文件接收
 * Created by asus on 2018/7/12.
 */
@Slf4j
@Component
public class ByteFileReceive  extends AbstractFileReceive {

    @Autowired
    private FileInfoCreator fileInfoCreator;

    @Override
    protected FileCreateDTO doReceiveFile(ByteFileReceiveRequest fileReceiveRequest) {

        //获取文件所有信息
        FileCreateDTO fileCreateDTO = fileInfoCreator.getInfo(fileReceiveRequest.getFileId(),
                fileReceiveRequest.getProName(),
                fileReceiveRequest.getContentType(),
                FileSizeTypeConf.ORIGINAL,
                fileReceiveRequest.getFileName(),
                fileReceiveRequest.getFileSize());
        //写入
        boolean writeFlag = fileWrite(fileReceiveRequest.getFileByte(),fileCreateDTO.getFilePath());
        if(!writeFlag){
            return null;
        }
        return fileCreateDTO;
    }

    private boolean fileWrite(byte[] fileByte,String file){
        boolean flag = false;
        //判断文件是否存在,不存在则创建
        File reciveFile = new File(file);
        if(!reciveFile.exists()){
            //创建文件
            //1.查看父类文件夹是否存在，不存在创建
            File parentDirFile = reciveFile.getParentFile();
            if(!parentDirFile.exists()){
                parentDirFile.mkdirs();
            }
            try {
                reciveFile.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        try (FileOutputStream outputStream = new FileOutputStream(reciveFile);){
            outputStream.write(fileByte,0,fileByte.length);
            outputStream.flush();
            flag = true;
        }catch (FileNotFoundException e) {
            log.error("文件或文件路径未找到");
        }catch (IOException e) {
            log.error("文件写入失败");
        }finally {
            return flag;
        }
    }
}
